﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using RuleCode.WinFormsUI.Docking;
using EnvDTE;

namespace RuleCode.ObjectTree
{
    public partial class OTControl : UserControl
    {
        #region 插件属性
        /// <summary>
        /// 获取或设置 VS插件对象
        /// </summary>
        public EnvDTE.DTE AddIn_ApplicationObject { get; set; }
        #endregion

        private readonly InfoWindow m_propertyWindow = new InfoWindow();
        private ObjectTreeForm m_objectTree;
        
        
        /// <summary>
        /// 重新初始化ObjectTree
        /// </summary>
        public void InitObjectTree()
        {
            {
                try
                {
                    ClearAOTs();                 
                    //m_objectTree.refreshOT();
                    //showAOT();
                    m_objectTree = new ObjectTreeForm(null); showAOT();
                }
                catch (Exception error)
                {
                    Util.SetStatusInfo(error.Message);
                    return;
                }
            }
            m_objectTree.ObjectInProp = ObjectInProp;
        }

        public void RefreshObjectTree()
        {
            if (m_objectTree != null)
                m_objectTree.refreshOT();
        }

        public OTControl()
        {
            InitOTControl();
            
        }

        public void InitOTControl()
        {
            this.Controls.Clear();
            //this.Dispose(true );
            if (!validateEnviroment())
            {
                MessageBox.Show("Configuration Error!");
                Application.Exit();

            }
            InitializeComponent();
            //log4net.Config.XmlConfigurator.Configure();
            //KeyPreview = true;

            //打开新窗口的显示模式
            Util.NewFormDisplayMode = NewFormDisplayMode.UserControl;
            Util.DockPanel_Property = DockPanel_Right;
            Util.DockPanel_Middle = DockPanel_Middle;
            Util.NewWindowCount = 0;
            Util.SplitContainer = LeftSplitContainer;
            Util.SplitContainer.Panel2Collapsed = true;
            Util.OTControl = this;
            Util.ContextMenuStrip_MiddleWin = ContextMenuStrip_MiddleWindow;

            //Util.Logger = logger;
            Util.DockPanel = DockPanel_Left;
            //Util.DockContainer = dockContainer1;
            //Util.DevArea = "GL";
            Util.DevArea = "DAT";
            Util.PropertyWindow = m_propertyWindow;
            //Util.MdiParent = this;
            showAOT();
            Util.setPropertyWindow(ObjectInProp);
            //this.OnClosing += new System.EventHandler(OnMDIParentClosing);
        }

        
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            showAOT();
        }
        private bool validateEnviroment()
        {
            bool ret = false;
            //初始化环境检查
            ret = true;
            return ret;

        }
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            Util.setPropertyWindow(ObjectInProp);
        }
       
        protected override void OnHandleDestroyed(EventArgs e)
        {
           
            //关闭程序时要做的事情

            //将最后一个Property序列化
            if (Util.CurrentProperty != null)
                Util.CurrentProperty.SerializeToXML();
            //Sort Table
            SysTreeView view = TreeViewOpr.getSysTreeView();
            view.ExpandAll();
            SysTreeNode root = (SysTreeNode)view.Nodes[0];
            XmlNode tables = root.SysXmlNode.SelectSingleNode("//表");
            NodesTransaction.Instance.SortXmlNode(tables);

            //Sort EDT
            DictClass dict = new DictClass();
            NodesTransaction.Instance.SortXmlNode(dict.EDTs.SysXmlNode);

            TreeViewOpr.saveOTXML();
            
            base.OnHandleDestroyed(e);
           
        }
        private void PropertyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            /**m_propertyWindow.ObjectInProp = ObjectInProp;
            m_propertyWindow.Show(dockPanel);
             **/
            Util.setPropertyWindow(ObjectInProp);
        }
            
        //public void refreshAllOT()
        //{
        //    foreach (Form chindForm in MdiChildren)
        //    {
        //        if (chindForm is ObjectTreeForm)
        //        {
        //            ObjectTreeForm OTForm = (ObjectTreeForm)chindForm;
        //            OTForm.refreshOT();
        //        }
        //    }
        //}

        private void ShowNewForm(object sender, EventArgs e)
        {
            /*// 创建此子窗体的一个新实例。
            Form childForm = new Form();
            // 在显示该窗前使其成为此 MDI 窗体的子窗体。
            childForm.MdiParent = this;
            childForm.Text = "窗口" + childFormNumber++;
            childForm.Show();*/
            showAOT();
        }

        //显示在属性窗体中的对象
        private Object objectInProp;

        public Object ObjectInProp
        {
            get { return objectInProp; }
            set { objectInProp = value; }
        }
        private void showAOT()
        {
          
                //dockPanel1.DocumentStyle = DocumentStyle.SystemMdi;
                Util.DockPanel = DockPanel_Left;
                //if (dockPanel1.DocumentStyle == DocumentStyle.SystemMdi)
                //{
                //    m_objectTree = new ObjectTreeForm(null);
                //    m_objectTree.MdiParent = this;
                //    Util.MdiParent = this;
                //    m_objectTree.ObjectInProp = ObjectInProp;
                //    m_objectTree.Show();
                //}
                //else
                {         try
                            {
                                if (m_objectTree == null)
                                {
                                    m_objectTree = new ObjectTreeForm(null);
                                        
                                }
                            }
                            catch (Exception error)
                            {
                                Util.SetStatusInfo(error.Message);
                                return;
                            }
                }
                m_objectTree.ObjectInProp = ObjectInProp;
                m_objectTree.Show(DockPanel_Left);      
                
        }
       
        /// <summary>
        /// 关闭以前打开的对象树
        /// </summary>
        private void ClearAOTs()
        {
            if (DockPanel_Left != null)
            {
                IDockContent[] allDockContents = DockPanel_Left.Contents.ToArray();
                for (int i = 0; i < allDockContents.Length; i++)
                {
                    try
                    {
                        DockContent content = allDockContents[i] as DockContent;     
                        content.Close();
                    }
                    catch { }
                }
            }
        }

        #region 中间DockPanel的窗口相关事件
        private void ToolStripMenuItem_CloseCurrentWindow_Click(object sender, EventArgs e)
        {
            if (Util.NewFormDisplayMode == NewFormDisplayMode.UserControl && Util.DockPanel_Middle !=null &&　Util.CurrentMiddleObjectTreeForm !=null)
            {
                Util.CurrentMiddleObjectTreeForm.Close();    
            }
        }

        private void ToolStripMenuItem_CloseOtherWindows_Click(object sender, EventArgs e)
        {
            Util.SetStatusInfo(Application.StartupPath );
            if (Util.NewFormDisplayMode == NewFormDisplayMode.UserControl && Util.DockPanel_Middle != null && Util.CurrentMiddleObjectTreeForm != null)
            {
                IDockContent[] allDockContents = Util.DockPanel_Middle.Contents.ToArray();
                for (int i = 0; i < allDockContents.Length; i++)
                {
                    try
                    {
                        DockContent content = allDockContents[i] as DockContent;
                        if (content != Util.CurrentMiddleObjectTreeForm)
                            content.Close();
                    }
                    catch { }
                }
            }
        }
        #endregion

        private void ToolStripButton_RefreshOT_Click(object sender, EventArgs e)
        {
            Util.SetBack();
            Util.InitCurrentProfileName();
            TreeViewOpr.Reload();
            InitObjectTree();
            //RefreshObjectTree(); 
        }

        private void ToolStripButton_CompareOT_Click(object sender, EventArgs e)
        {
            ProjectItem projectItem = Util_DTE.FindProjectItem(AddIn_ApplicationObject.Solution.Projects.Item(1), "");
            //if(AddIn_ApplicationObject !=null )
                
        }
    }
}
